package com.starry.home.ui.main

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.drake.brv.BindingAdapter
import com.drake.brv.utils.setup
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.util.TextInfo
import com.starry.core.base.BaseActivity
import com.starry.core.constant.GlobalConfig
import com.starry.core.ext.singleClick
import com.starry.core.ext.toast
import com.starry.core.utils.SpUtil
import com.starry.core.utils.ZKStatusBarUtil
import com.starry.home.R
import com.starry.home.databinding.ActivityMedicalBinding
import com.starry.home.logic.model.medical.MedicalBean
import com.starry.home.logic.model.medical.XyModelEntity
import com.starry.home.logic.model.medical.ZyModelEntity
import com.starry.home.ui.dialog.LoadingAlertDialog
import com.starry.home.utils.DateUtils
import com.starry.home.viewmodel.main.MedicalViewModel
import java.util.Date

/**
 * Package:com.starry.dotpen_patients.ui.main
 * Author:starr
 * Time:2024/1/28 21:16
 * Description: 展示用户病历本
 */
class MedicalActivity : BaseActivity<ActivityMedicalBinding, MedicalViewModel>() {

    private lateinit var mRvMedical: RecyclerView
    private lateinit var mMedicalAdapter: BindingAdapter
    private lateinit var mLoadingDialog: LoadingAlertDialog

    private lateinit var mZyMedicalList: ArrayList<ZyModelEntity>
    private lateinit var mXyMedicalList: ArrayList<XyModelEntity>
    private var isXySelect = true
    private var mUserBlId = 0

    companion object {
        fun startAction(context: Context) {
            val intent = Intent(context, MedicalActivity::class.java)
            context.startActivity(intent)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initData() {
        mViewModel.userBl.observeForever { it ->
            if (it.isSuccess) {
                it.getOrNull()?.let { medicalBean ->
                    if (medicalBean.blEntity == null) {
                        mLoadingDialog.dismiss()
                        createNewBook()
                        toast("暂无病历本")
                        return@observeForever
                    }
                    mUserBlId = medicalBean.blEntity!!.emrBlId
                    mViewModel.getXyMedical(mUserBlId)
                }
            }
        }

        mViewModel.xyMedical.observeForever { it ->
            if (it.isSuccess) {
                mLoadingDialog.dismiss()
                it.getOrNull()?.let { result ->
                    mMedicalAdapter.models = result.jdList.map { it ->
                        it.modelEntity
                    }.toMutableList<XyModelEntity>()
                    if (result.jdList.isEmpty()) {
                        toast("暂无西医病历")
                        return@observeForever
                    } else {
                        toast("西医病历")
                    }
                    mMedicalAdapter.notifyDataSetChanged()
                }
            }
        }

        mViewModel.zyMedical.observeForever { it ->
            if (it.isSuccess) {
                mLoadingDialog.dismiss()
                it.getOrNull()?.let { result ->
                    mMedicalAdapter.models = result.jdList.map { it ->
                        it.zyModelEntity
                    }.toMutableList<ZyModelEntity>()
                    if (result.jdList.isEmpty()) {
                        toast("暂无中医病历")
                        return@observeForever
                    } else {
                        toast("中医病历")
                    }
                    mMedicalAdapter.notifyDataSetChanged()
                }
            }
        }

        mViewModel.createNewBook.observeForever { it ->
            if (it.isSuccess) {
                toast("创建成功")
                finish()
            }
        }
    }

    private fun createNewBook() {
        MessageDialog.show("提示", "您暂无病历本，是否创建新的病历本？", "创建", "取消")
            .setOkTextInfo(TextInfo().setFontColor(getColor(R.color.colorPrimaryPlus)))
            .setCancelTextInfo(TextInfo().setFontColor(getColor(R.color.colorCancel)))
            .setOkButton { dialog, _ ->
                val medicalBean = MedicalBean.BlEntity()
                medicalBean.emrBlCreate =
                    DateUtils.date2String(Date(), DateUtils.yyyyMMddHHmmSS.get())
                medicalBean.emrBlUpdate =
                    DateUtils.date2String(Date(), DateUtils.yyyyMMddHHmmSS.get())
                medicalBean.emrHzId = SpUtil.getIntValue(GlobalConfig.userId)
                mViewModel.createNewBook(medicalBean)
                dialog.dismiss()
                false
            }
    }

    override fun initView() {
        mLoadingDialog = LoadingAlertDialog(getContext())
        initTitleBar()
        mRvMedical = mDataBinding.rvMedical
        initChangeTab()

        val linearLayoutManager = LinearLayoutManager(getContext())
        linearLayoutManager.stackFromEnd = true
        linearLayoutManager.reverseLayout = true
        mRvMedical.layoutManager = linearLayoutManager
        mMedicalAdapter = mRvMedical.setup {
            addType<ZyModelEntity>(R.layout.item_zy_node)
            addType<XyModelEntity>(R.layout.item_meidcal_node)
            onBind {
                when (val models = getModel<Any>()) {
                    is ZyModelEntity -> {
                        setRvZyContent(models)
                    }

                    is XyModelEntity -> {
                        setRvXyContent(models)
                    }
                }
            }
        }
        val userId = SpUtil.getIntValue(GlobalConfig.userId)
        if (userId == -1) {
            toast("登录状态失效，请重新登录")
        } else {
            mViewModel.getUserBl(SpUtil.getIntValue(GlobalConfig.userId))
            mLoadingDialog.show()
        }
    }

    private fun initChangeTab() {
        mDataBinding.clTabChange.setOnClickListener {
            if (mUserBlId == 0) {
                toast("暂无病历本")
                return@setOnClickListener
            }
            if (isXySelect) {
                mDataBinding.tvTabXy.setBackgroundResource(R.drawable.corner_gray_30)
                mDataBinding.tvTabZy.setBackgroundResource(R.drawable.corner_select_30)
                mViewModel.getZyMedical(mUserBlId)
                mLoadingDialog.show()
            } else {
                mDataBinding.tvTabXy.setBackgroundResource(R.drawable.corner_select_30)
                mDataBinding.tvTabZy.setBackgroundResource(R.drawable.corner_gray_30)
                mViewModel.getXyMedical(mUserBlId)
                mLoadingDialog.show()
            }
            isXySelect = !isXySelect
        }
    }

    private fun BindingAdapter.BindingViewHolder.setRvXyContent(model: XyModelEntity) {
        val tvDate = findView<TextView>(R.id.tv_date)
        tvDate.text = model.emrXyDate.substring(0, 10)
        val tvChief = findView<TextView>(R.id.tv_chief_1)
        val tvDeal = findView<TextView>(R.id.tv_deal_1)
        val tvYsName = findView<TextView>(R.id.tv_create_people)
        val tvTime = findView<TextView>(R.id.tvTime)
        tvChief.text = model.emrXyMain
        tvDeal.text = model.emrXyDeal
        tvYsName.text = model.emrYsName
        tvTime.text = model.emrXyDate.substring(0, 10)

        findView<TextView>(R.id.tvRecovery).singleClick {
            RecoveryActivity.startAction(getContext())
        }
    }

    private fun BindingAdapter.BindingViewHolder.setRvZyContent(model: ZyModelEntity) {
        val tvDate = findView<TextView>(R.id.tv_date)
        tvDate.text = model.emrZyDate.substring(0, 10)
        val tvChief = findView<TextView>(R.id.tv_chief_1)
        val tvResult = findView<TextView>(R.id.tvResult_1)
        val tvDrug = findView<TextView>(R.id.tvDrug_1)
        val tvYsName = findView<TextView>(R.id.tv_create_people)
        val tvTime = findView<TextView>(R.id.tvTime)
        tvChief.text = model.emrZyMain
        tvResult.text = model.emrZyResult
        tvDrug.text = model.emrZyDrugs
        tvYsName.text = model.emrYsName
        tvTime.text = model.emrZyDate.substring(0, 10)

        findView<TextView>(R.id.tvRecovery).singleClick {
            RecoveryActivity.startAction(getContext())
        }
    }

    private fun initTitleBar() {
        mDataBinding.titleTopBar.baseTvTitle.text = "病历本"
        mDataBinding.titleTopBar.baseIvBack.setOnClickListener {
            finish()
        }
        ZKStatusBarUtil.setTransparentForWindow(this)
        ZKStatusBarUtil.setDarkMode(this)
    }


    override fun getLayoutId() = R.layout.activity_medical
}